import 'package:get/get.dart';
import 'package:xin_he/page/mine/xin_he_adress_management/model/xin_he_address_item_model_entity.dart';
import 'package:xin_he/utils/xin_he_user_data.dart';

import '../../../service/xin_he_reqest.dart';
import '../../../utils/xin_he_event_bus.dart';
import '../../../utils/xin_he_storage.dart';
import '../../../utils/xin_he_toast.dart';
import 'xin_he_adress_management_state.dart';

class XinHeAdressManagementLogic extends GetxController {
  final XinHeAdressManagementState state = XinHeAdressManagementState();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    // for(int i = 0 ;i<5;i++){
    //   XinHeAdressModel model = XinHeAdressModel();
    //   state.list.add(model);
    // }


  }

  @override
  void onReady() {
    // TODO: implement onInit
    super.onReady();


    requestAddresses();
  }

  refreshData() {
    requestAddresses();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  requestAddresses() async{

    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);
    Map<String,dynamic>map = {
      // 'orderStatus':type,
      'userId': userId
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/address/findAddressList',params: map,isPost: false);

    if(!result.result|| result.data['code'] != 0){
      XinHeToast.center(result.data['message']);
      return ;
    }
    List list = result.data['data'] ??[];
    List items = [];
    if(list.isNotEmpty){
      for(var e in list){
        XinHeAddressItemModelEntity model = XinHeAddressItemModelEntity.fromJson(e);
        items.add(model);
      }
      state.list.value = items;
    }else {
      state.list.clear();
    }
  }

  deleteItem(int id) async{
    Map<String,dynamic>map = {
      'addressId':id
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/address/deleteAddress',params: map,isPost: false);

    if(!result.result|| result.data['code'] != 0){
      XinHeToast.center(result.data['message']);
      return ;
    }
    XinHeToast.center('删除成功');
    refreshData();



  }


  settingItemDefault(int id) async{
    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);

    Map<String,dynamic>map = {
      'userId': userId,
      'addressId':id,
      'isdefault':1
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/address/saveDefaultAddress',params: map,isPost: true,isPostAndwwwForm: true);

    if(!result.result|| result.data['code'] != 0){
      XinHeToast.center(result.data['message']);
      return ;
    }
    XinHeToast.center('修改默认成功');
    bus.emit(XinHeStorage.settingDefaultAddress);
    refreshData();



  }

}
